<?php
/*
RPHP Controller
@category  Core
*/
class RPHP_Controller
{
	
	
	protected $_modelsHome = null;
    protected $_viewsHome = null;
	protected $_router = null;
	protected $c = null;
	
	
	public function __construct($config,$router)
	{		
		$this->c = $config;
		if (null === $this->_modelsHome) {
            $this->_modelsHome = $config['_homes']['_modelsHome'];
        }
        if (null === $this->_viewsHome) {
            $this->_viewsHome = $config['_homes']['_viewsHome'];
        }
		
		$this->_router = $router;
	}
	
	protected function defaultTemplate()
    {
        return $this->_router['deftpl'];
    }
	
	protected function model($name = null, $dir = null)
    {
       	if (null === $name) {
            return $this->model;
        }

        null === $dir && $dir = $this->_modelsHome;
        $class = strtolower($name) . 'Model';		
        if (RPHP::loadClass($name, $dir)) {
            return new $class($this->c);
        }
    }
	
	protected function view()
    {       

        return $this->view = new RPHP_View($this->c);
    }

    /**
     * Display the view
     *
     * @param string $tpl
     */
    protected function display($tpl = null,$_global_dir = false, $dir = null)
    {
		if (empty($tpl)) $tpl = $this->defaultTemplate();
		
		if($_global_dir) $dir = $this->_viewsHome.DIRECTORY_SEPARATOR."_global";
		elseif( empty($dir)) $dir = $this->_viewsHome.DIRECTORY_SEPARATOR.$this->_router['model'];		
		
        $this->view->display($tpl, $dir);
    }
	
	protected function displaydo()
	{
		$this->display("do",true);
	}

    public static function redirect($url, $code = null)
    {
        header("Location:$url", true, $code);
        exit();
    }
	
	public function __set($key, $value = null)
    {
        $this->$key = $value;
    }

	
	public function __get($key)
    {
        switch ($key) {
           	case 'view':
                $this->view();
                return $this->view;
            case 'model':
                $class = get_class($this);
                $this->model = $this->model(substr($class, 0, -10));
                return $this->model;
			default:
                
        }
    }
	
}
?>